<?php
namespace My\Controller;

use Utuo\BackgroundController;
use My\Model\ProductOrderModel;
use Utuo\PHPExcel;

class BelongingsController extends BackgroundController {
	
	private $pid = 0;
	
	protected $types = array('0'=>'自卖', '1' => '他卖', '2'=>'代卖');
	
	public function _initialize() {
		$this->setControllerTitle("财物管理");
		$this->setActionTitle(array(
				'index' => '出售列表',
		));
		$this->setActionNav("index");
		$this->pid = session("pid");
	}
	
	public function indexAction() {
		$type = I('type', 0, 'intval');
		$startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
		$endDate = I('endDate', 0, 'intval') or $endDate = time();
		$params = array(
				'type' => $type,
				'startDate' => $startDate,
				'endDate' => $endDate,
		);
		$productOrderGoodsLists = $this->search( $params );
		$typesRadio = $this->getRadio("type", $this->types, $type);
		$this->assign('typesRadio', $typesRadio);
		$this->assign("params", $params);
		$this->assign("productOrderGoodsLists", $productOrderGoodsLists);
		$this->display();
	}
	
	/**
	 * 导出Excel
	 */
	public function exportXLSAction() {
		$type = I('type', 0, 'intval');
		$startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
		$endDate = I('endDate', 0, 'intval') or $endDate = time();
		$params = array(
				'type' => $type,
				'startDate' => $startDate,
				'endDate' => $endDate,
		);
		$productOrderGoodsLists = $this->search( $params );
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setCreator("微美风铃")
					->setLastModifiedBy("微美风铃")
					->setTitle("销售报表")
					->setSubject("销售报表")
					->setDescription("销售报表")
					->setKeywords("销售 报表")
					->setCategory("报表");

		
		/*设置标题*/
		$titles = array('ID','订单编号','商品名称','分成比例(合作商:商品主:经销商)','我的分成','成交日期');
		$fields = array('id' => array('type'=>'number'),
						'order_id'=> array('type'=>'string'), 
						'product_name'=> array('type'=>'string'), 
						'percent' => array('type'=>'string'), 
						'mygot' => array('type'=>'string'), 
						'deal_time'=>array('type'=>'datetime', 'format' => 'Y/m/d h:i:s'));
		$sheet0 = $objPHPExcel->setActiveSheetIndex(0);
		$rowNumber = 1;
		foreach ($titles as $k => $v) {
			$sheet0->setCellValue(chr(ord('A')+$k).$rowNumber, $v);
		}
		$rowNumber++;
		foreach ( $productOrderGoodsLists as $v ) {
			$fieldIndex = 0;
			foreach ( $fields as $k0 => $v0 ) {
				$cellName = chr(ord('A')+$fieldIndex++).$rowNumber;
				$sheet0->setCellValueExplicit($cellName, $this->getShowData($v[$k0], $v0), $this->getCellFormat($v[$k0]));
				//$sheet0->setCellValue(chr(ord('A')+$fieldIndex++).$rowNumber, $this->getShowData($v[$k0], $v0));
			}
			$rowNumber++;
		}
		$objPHPExcel->getActiveSheet()->setTitle(date('Y年m月d', time($startDate)).'至'.date('Y年m月d', time($endDate))."销售报表");
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.date("Ymdhis").'.xls"');
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1'); // IE9时
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
	}
	
	/**
	 * 获得单元格格式
	 * @param unknown $fieldCfg
	 * @return string
	 */
	private function getCellFormat( $fieldCfg ) {
		if( $fieldCfg['type'] == 'string' ) {
			return \PHPExcel_Cell_DataType::TYPE_STRING;
		}
		return \PHPExcel_Cell_DataType::TYPE_STRING;
	}
	
	
	/**
	 * 获得数据展示格式 
	 * @param unknown $value
	 * @param unknown $fieldCfg
	 * @return string|unknown
	 */
	private function getShowData($value, $fieldCfg) {
		if( $fieldCfg['type'] == 'datetime' ) {
			return date( $fieldCfg['format'], $value);
		}
		return $value;
	}
	
	/**
	 * 查询
	 * @param unknown $params
	 * @return unknown
	 */
	private function search( $params, $paginate = true ) {
		$type = $params['type'];
		$page = $this->getPage();
		$condition = array(
			'b.pid' => $this->pid,
			'b.order_status' => ProductOrderModel::ORDER_STATUS_COMPLETED,
			'b.deal_time' => array(array('egt', $params['startDate']), array('elt', $params['endDate']), 'and'),
		);
		$field = "a.*,b.cid,b.order_id,b.deal_time";
		if( $type == 0 ) { // 商品主与经销商为一
			$condition['a.owner_cid'] = array('exp', "=b.cid and a.owner_cid={$this->aid}");
			$field.=",a.customer_got+a.seller_got as mygot";
		} elseif( $type == 1 ) { // 他人帮我卖的
			$condition['a.owner_cid'] = array('exp', "!=b.cid and a.owner_cid={$this->aid}");
			$field.=",a.customer_got as mygot";
		} elseif( $type == 2 ) { // 我帮别人卖的
			$condition['a.owner_cid'] = array('neq', $this->aid);
			$condition['b.cid'] = array('eq',  $this->aid);
			$field.=",a.seller_got as mygot";
		}
		$m = M("ProductOrderGoods a")->join("__PRODUCT_ORDER__ b on a.order_id=b.id", "LEFT")->where($condition);
		$n = clone $m;
		if( $paginate ) {
			$totalRows = $n->count();
			$m->page($page)->limit($this->getPageSize());
			$this->showPage($totalRows, $this->pageSize);
		}
		$productOrderGoodsLists = $m->field($field)->select();
		return $productOrderGoodsLists;
	}
	
}